/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.transformation;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class BuilderCache {

    private final Map<File, XsltSingleSourceConditionedBuilder> marcEseCache = new HashMap<File, XsltSingleSourceConditionedBuilder>();
    private final Map<File, XsltSingleSourceConditionedBuilder> marcDcCache = new HashMap<File, XsltSingleSourceConditionedBuilder>();
    private final Map<File, XsltSingleSourceConditionedBuilder> teiEseCache = new HashMap<File, XsltSingleSourceConditionedBuilder>();

    SingleSourceTransformer getMarcBasedXsltEseBuilder(File xslt) throws TransformationException {
        return getBuilder(marcEseCache, xslt, MarcBasedXsltEseBuilder.class);
    }

    SingleSourceTransformer getMarcBasedOaiDcBuilder(File xslt) {
        return getBuilder(marcDcCache, xslt, MarcBasedOaiDcBuilder.class);
    }

    SingleSourceTransformer getTeiBasedXsltEseBuilder(File xslt) {
        return getBuilder(teiEseCache, xslt, TeiBasedXsltEseBuilder.class);
    }

    private SingleSourceTransformer getBuilder(Map<File, XsltSingleSourceConditionedBuilder> cache, File xslt, Class clas) {
        XsltSingleSourceConditionedBuilder result = cache.get(xslt);
        if (result == null) {
            try {
                System.out.println("adding " + clas.getCanonicalName() + " for " + xslt.getAbsolutePath());
                Constructor constructor = clas.getConstructor(File.class);
                result = (XsltSingleSourceConditionedBuilder) constructor.newInstance(xslt);
                cache.put(xslt, result);
            } catch (InstantiationException ex) {
                Logger.getLogger(BuilderCache.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(BuilderCache.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(BuilderCache.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
                Logger.getLogger(BuilderCache.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(BuilderCache.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(BuilderCache.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
           //System.err.println("found builder in cache: " + clas.getCanonicalName() + " for " + xslt.getAbsolutePath());
        }
        return result;
    }
}
